package com.lpit.config;

import com.lpit.constant.Constant;
import com.lpit.dto.AdminDto;
import com.lpit.exception.AdminException;
import com.lpit.mapper.SysAdminMapper;
import com.lpit.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component()
public class UserDServiceImpl implements UserDetailsService {

    @Autowired
    private SysAdminMapper sysAdminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过s(账号) 到数据中查询数据 并将数据封装到User(是springsecurity提供的User对象)对象中
        List<GrantedAuthority> grantedAuthorityArrayList = new ArrayList<>();
        /*根据用户id查询用户角色跟权限*/
        AdminDto adminDto = sysAdminMapper.getRoleAndJurisById(username);
        if (Objects.isNull(adminDto)) {
            throw new AdminException(Constant.MESSAGE_LOGIN_FAILED);
        }
        /*将角色个跟权限放入Security中*/
        //new SimpleGrantedAuthority("ROLE_xxx");// 封装角色 和 权限
        for (SysRole sysRole : adminDto.getRoles()) {
            System.out.println("角色：" + sysRole.getRole());
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(Constant.SECURITY_ROLE + sysRole.getRole());
            grantedAuthorityArrayList.add(simpleGrantedAuthority);
        }
        for (SysJurisdiction sysJurisdiction : adminDto.getJurisdictions()) {
            System.out.println("权限：" + sysJurisdiction.getJurisdictionRequest());
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(sysJurisdiction.getJurisdictionRequest());
            grantedAuthorityArrayList.add(simpleGrantedAuthority);
        }
        return new User(adminDto.getUsername(), new BCryptPasswordEncoder().encode(adminDto.getPassword()), grantedAuthorityArrayList);
    }
}
